const {MongoClient} = require('mongodb')
const url = 'mongodb://admin:admin@192.168.20.130:27017'
const client = new MongoClient(url)

const dbName = 'node-db'
const collectionName = "location";

/**
 *添加数据到数据库
 * @param { Array} data
 * @returns string
 */
const insertMany = async (data) => {
    // Use connect method to connect to the server
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection(collectionName);
    await collection.insertMany(data);
    await client.close();
    return "done.";
}

/**
 * 清空数据库
 */
const deleteMany = async () => {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection(collectionName);
    await collection.deleteMany();
    await client.close();
    return "done.";
}

/**
 * 获取数据集
 * @returns array
 */
const getData = async () => {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection(collectionName);
    const array = await collection.find().toArray();
    await client.close();
    return array;
}

module.exports = {
    insertMany,
    getData,
    deleteMany
}
